← Back

JavaScript Fetch Method Practice Exercise

This exercise helps you practise the basic fetch() workflow with a public test API.

The goal is to request posts from JSONPlaceholder, check the response, convert the response to JSON, and render the data on the page.

1. What you are practising

2. Fetch flow

Browser
-> fetch(url)
-> server receives request
-> server sends response
-> check response.ok
-> response.json()
-> render data

3. Basic pattern

fetch("https://jsonplaceholder.typicode.com/posts")
    .then((response) => {
        if (!response.ok) {
            throw new Error(response.statusText);
        }

        return response.json();
    })
    .then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.error(error);
    });

4. Add query parameters

JSONPlaceholder supports the _limit parameter. It controls how many posts come back.

const params = new URLSearchParams({
    _limit: 5
});

const url = `https://jsonplaceholder.typicode.com/posts?${params}`;

5. Working practice version

Choose how many posts to load and click the button. Then read the script below the form and try rebuilding it from memory.

6. Practice steps

  1. Create variables for the form, status text, and list.
  2. Add a submit event listener to the form.
  3. Use event.preventDefault() to stop the page reload.
  4. Read event.currentTarget.elements.limit.value.
  5. Create a URLSearchParams object with _limit.
  6. Call fetch() with the final URL.
  7. Check response.ok.
  8. Return response.json().
  9. Use .then() to render the posts.
  10. Use .catch() to handle errors.

7. Important idea

fetch() does not give you the final data immediately. It gives you a Promise.

That means you work with the result inside .then(), or later with async and await.

const result = fetch(url);

console.log(result);
// Promise, not final posts data

← Back